package com.apes.scm.sal.saleReturn;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.ledger.service.LedgerService;
import com.apes.scm.masterdata.party.model.PartyRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("saleReturnNoOrderService")
public class SaleReturnNoOrderService extends DomainService {
    @Autowired
    private SaleReturnRepository saleReturnRepository;
    @Autowired
    private LedgerService ledgerService;
    @Autowired
    private SequenceService sequenceService;

    /***
     * 功能: 创建
     * @param request
     * @return
     */
    public SaleReturn create(SimpleRequest request){
        SaleReturn saleReturn = request.getO(SaleReturn.class);
        if (saleReturn.getSaleReturnItems().isEmpty()) throw new RuntimeException("订单明细行数据有误，请检查后，重新保存！");
        saleReturn.computeAmt(); // 合计金额
        String companyId = request.getCurrentCompany() == null ? "" : ((PartyRole)request.getCurrentCompany()).getId();
        saleReturn.setId("FV" + companyId + sequenceService.getId(SaleReturn.CONST_TABLE_NAME));
        // 回写会员扩展表逻辑
        if (saleReturn.getSaleOrder() != null && saleReturn.getSaleOrder().getFnCustomerExpandId() != null){
            saleReturn.setFnCustomerExpandId(saleReturn.getSaleOrder().getFnCustomerExpandId());
        }

        saleReturn.setInvoiceStatus("no");
        saleReturn.setState("sent");

        // 设置退货冲红数量为退货数量
        saleReturn.getSaleReturnItems().forEach(saleReturnItem -> saleReturnItem.setQtyDelivered(saleReturnItem.getProductUomQty()));

        return saleReturnRepository.saveAndFlush(saleReturn);
    }


    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public SaleReturn update(SimpleRequest request){
        SaleReturn saleReturn = request.getO(SaleReturn.class);

        // 设置退货冲红数量为退货数量
        saleReturn.getSaleReturnItems().forEach(saleReturnItem -> saleReturnItem.setQtyDelivered(saleReturnItem.getProductUomQty()));

        return saleReturnRepository.saveAndFlush(saleReturn);
    }

    /***
     * 功能：删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request){
        String id = request.get("id");
        SaleReturn saleReturn = saleReturnRepository.findOne(id);
        if (saleReturn == null) throw new RuntimeException("订单：" + request.get("id") + " 在系统中不存在。");
        if (saleReturn.getState().equals("confirmed")) throw new RuntimeException("订单：" + request.get("id") + " 在系统中已审批。");
        saleReturnRepository.delete(saleReturn);
        return "删除成功";
    }

    /***
     * 功能：审核
     * @param request
     * @return
     */
    public SaleReturn approve(SimpleRequest request){
        String id = request.get("id");
        SaleReturn saleReturn = saleReturnRepository.findOne(id);
        check(request, saleReturn);
        saleReturn.setState("confirmed");
        saleReturn.setDateApprove(new Date());
        SaleReturn nSaleReturn = saleReturnRepository.saveAndFlush(saleReturn);

        nSaleReturn.setShipped(); // 判断订单是否完成
        if (nSaleReturn.getState().equals("done")) nSaleReturn = saleReturnRepository.saveAndFlush(nSaleReturn);
        return nSaleReturn;
    }

    private void check(SimpleRequest request, SaleReturn saleReturn) {
        if (saleReturn == null) throw new RuntimeException("订单：" + saleReturn.getId() + " 在系统中不存在。");
        if (saleReturn.getSaleReturnItems().isEmpty()) throw new RuntimeException("订单明细行缺失，请重新做单！");
        if (saleReturn.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        if (saleReturn.getState().equals("confirmed")) throw new RuntimeException("订单：" + saleReturn.getId() + " 在系统中已审批。");
        if (!saleReturn.getCompany().getId().equals(saleReturn.getLocation().getCompany().getId())) throw new RuntimeException("订单：" + saleReturn.getId() + " 仓库公司与单据公司不一致。");
    }


    /***
     * 功能：findOne
     * @param request
     * @return
     */
    public SaleReturn findOne(SimpleRequest request){
        Map params = MapUtil.mapper("orderType.code", "B", "id", request.get("id"));
        List<SaleReturn> list = saleReturnRepository.findAll(JpaDsl.toCriteria(params));
        if( list != null && list.size() > 0 ) return  list.get(0);
        return null;
    }



    /**
     * 写入总账
     */
    private void charge(SaleReturn saleReturn, String ledgerAccount, Double incurred) {
        ledgerService.charge(saleReturn.getCompany(), saleReturn.getDept(), saleReturn.getCustomer(),
                saleReturn.getCooperation().getInventoryMode(), saleReturn.getCooperation().getAccountingMethod(),
                saleReturn.getId(), saleReturn.getClass().getSimpleName(), new Date(), ledgerAccount, incurred);
    }
}
